<?php

namespace APP\Ctrl;
use CMS\Ctrl as Base;
use CMS\Helper as Helper;

class Forgot extends Base {
	// construct
	public function run() {
		// already logged in?
		if(isset($this->session->auth))
			die(new Index());

		// manage uri paths
		if(count($this->uri) > 0) {
			@list($func, $id) = $this->uri;
			$this->$func($id ? $id : 'null');
		} else $this->index();
	}

	// index
	public function index() {
		$this->view->func = 'index';

		// set path
		$this->view->path = array(
			'func' => $this->view->func
		);
	}

	// reset password
	public function reset($token) {
		$this->view->func = 'reset';

		// set title
		$this->view->title .= ' / Change Password';

		// null token?
		if($token == 'null')
			die(new Error());

		// decode password, time and id
		$token = base64_decode($token);
		$password = substr($token, 0, 16) . substr($token, 26, 16);
		$time = substr($token, 16, 10);
		$id = substr($token, 42);

		// expected 32 length password
		if(!(!empty($password) && strlen($password) == 32))
			die(new Error());

		// expected 10 length timestamp (10 length till year 2286 :))
		if(!(is_numeric($time) && (int)$time == $time && strlen($time) == 10))
			die(new Error());

		// expected id
		if(!(is_numeric($id) && (int)$id == $id))
			die(new Error());

		// check whether the time is in the past
		if(!($time < time()))
			die(new Error());

		// if time is older than 1 week discard
		if($time < strtotime("-1 week"))
			die(new Error());

		// database prepare
		$id = $this->db->escapeString((int)$id);
		$password = $this->db->escapeString((string)$password);

		// match against db
		$result = $this->db->querySingle("SELECT * FROM users WHERE id = '{$id}' AND password = '{$password}'", true);
		if(!$result)
			die(new Error());

		// send to view
		$this->view->data = $result;
		$this->view->data['avatar'] = md5(strtolower($result['email']));
		$this->view->data['link'] = $result['id'] . '-' . Helper::generate_named_id($result['name']);
		$this->view->token = base64_encode($result['password'] . $result['id']);

		// set path
		$this->view->path = array(
			'func' => $this->view->func
		);
	}

	// ajax send reset email
	public function submit() {
		// get from post
		$email = $this->request->post('email');
		$name = $this->request->post('name');
		if(is_null($email) && is_null($name))
			return $this->json = array('success' => false);

		// process vars
		$email = $this->db->escapeString(strtolower($email));
		$name = $this->db->escapeString(strtolower($name));

		// option a
		if(!empty($email)) {
			// check for email
			$result = $this->db->querySingle("SELECT * FROM users WHERE lower(email) = '{$email}'", true);
			if(!$result)
				return $this->json = array('success' => false);
		}

		// option b
		if(!empty($name)) {
			// check for name
			$result = $this->db->querySingle("SELECT * FROM users WHERE lower(name) = '{$name}'", true);
			if(!$result)
				return $this->json = array('success' => false);
		}

		// build reset token
		$token = (string)substr($result['password'], 0, 16) . time() . substr($result['password'], 16, 32) . $result['id'];

		// send a nice email :)
		$eml = Helper::load_email('forgot.txt', $result['name'], URL . 'forgot/reset/' . base64_encode($token), $this->settings['blizz_guild']);
		if($eml)
			$this->email->send($result['email'], $result['name'], $eml);

		// here? then everything worked!
		return $this->json = array('success' => true);
	}

	// ajax change password
	public function change() {
		// get from post
		$token = $this->request->post('token');
		$password = $this->request->post('password');
		if(is_null($token) || is_null($password))
			return $this->json = array('success' => false);

		// decode token
		$info = base64_decode($token);
		$id = $this->db->escapeString((int)substr($info, 32));
		$oldpass = $this->db->escapeString((string)substr($info, 0, 32));

		// match against db
		$result = $this->db->querySingle("SELECT id, name, email FROM users WHERE id = '{$id}' AND password = '{$oldpass}'", true);
		if(!$result)
			return $this->json = array('success' => false);

		// process vars
		$password = md5(sha1($password . SALT1) . SALT2);

		// update password
		$this->db->exec("UPDATE users SET password='{$password}' WHERE id = '{$result['id']}'");

		// send a nice email :)
		$eml = Helper::load_email('password.txt', $result['name'], URL . 'forgot', $this->settings['blizz_guild']);
		if($eml)
			$this->email->send($result['email'], $result['name'], $eml);

		// set as logged in
		$this->cookie->auth = base64_encode($password . $result['id']);

		// yay success
		return $this->json = array('success' => true, 'user' => array(
			'name' => $result['name']
		));
	}
}